package com.qf.commons.web.exception.handler;

import com.qf.commons.standar.exception.IExceptionHandler;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

import javax.validation.ConstraintViolationException;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 参数校验异常的处理器
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Component
public class BindExcetionHandler implements IExceptionHandler {

    @Override
    public boolean isSupport(Exception e) {
        return e.getClass() == BindException.class || e.getClass() == ConstraintViolationException.class;
    }

    @Override
    public R exceptionHandler(Exception e) {

        Map<String, String> result = null;

        if (e instanceof BindException) {
            //强转成为绑定异常
            BindException bindException = (BindException) e;
            result = bindException.getAllErrors().stream()
                    .collect(Collectors.toMap(
                            objectError -> objectError.getCodes()[1],
                            objectError -> objectError.getDefaultMessage()
                    ));
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
            result = constraintViolationException.getConstraintViolations().stream()
                    .collect(Collectors.toMap(
                            constraintViolation -> constraintViolation.getPropertyPath().toString(),
                            constraintViolation -> constraintViolation.getMessageTemplate()
                    ));
        }

        return Rs.createFail(Codes.PARAM_ERROR, result);
    }
}
